<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSON-CLASS转换</title>
</head>
<style>
    .source {
        width: 45%;
        margin: 0;
        padding: 0;
        float: left;
    }

    .target {
        width: 45%;
        margin: 0;
        padding: 0;
        float: left;
        color: rgb(24, 145, 243);
    }
</style>
<body>
<textarea id="json-source" class="source" cols="30" rows="10" spellcheck="false"></textarea>
<textarea id="class-target" class="target" cols="30" rows="10" spellcheck="false"></textarea>
<p>
    <button id="convert">转换</button>
</p>
<script>
    var source = document.querySelector('#json-source');
    var target = document.querySelector('#class-target');

    function toHump(str) {
        if (str.indexOf('_') >= 0) {
            var arr = str.split('_');
            var res = arr[0];
            for (var i = 1; i < arr.length; i++) {
                var s = arr[i];
                var peffix = s.substr(0, 1).toUpperCase();
                var suffix = s.substr(1, s.length - 1);
                res += (peffix + suffix);
                return res;
            }
        }
        return str;
    }

    function toField(k, v) {
        var type = 'String';
        switch (typeof v) {
            case 'string' :
                type = 'String';
                break;
            case 'number' :
                if (v.toString().indexOf('.') >= 0) {
                    type = 'Double';
                } else {
                    type = 'Integer';
                }
                break;
            case 'boolean':
                type = "Boolean";
                break;
            case 'object':
                if (Array.isArray(v)) {
                    type = 'List<Object>';
                } else {
                    type = 'Map<String,Object>';
                }
                break;
        }
        if (k.indexOf('_') >= 0) {
            return '\t@JSONField(name="' + k + '")\r\n\tprivate ' + type + ' ' + toHump(k) + ';\r\n';
        } else {
            return '\tprivate ' + type + ' ' + k + ';\r\n';
        }
    }

    document.querySelector('#convert').onclick = function (ev) {
        try {
            var json = JSON.parse(source.value);
            var classStr = '';
            for (var k in json) {
                classStr += toField(k, json[k]);
            }
            var classHeader = 'import com.alibaba.fastjson.annotation.JSONField;\r\nimport lombok.Data;\r\n\r\n\r\n@Data\r\nclass Someone{\r\n';
            var classFooter = '}';
            classStr = classHeader + classStr + classFooter;
            target.value = classStr;
        } catch (e) {
            alert(e.message);
        }
    };
</script>
</body>
</html>